import logging
import datetime
import re
from enum import IntEnum
from native.common.excel import Excel
from backend.po.buy_order import BuyOrder

class DateTimeStringParser(object):
    def __init__(self, s):
        self.__s = s

    def parse(self):
        pattern = "^(\d+)年(\d+)月(\d+)日"
        match = re.search(pattern, self.__s)
        if match : 
            m = match.groups()
            if len(m) == 3:
                year = int(m[0])
                month = int(m[1])
                day = int(m[2])
                if month > 0 and month <= 12 and day > 0 and day <= 31:
                    return (year, month, day)
                else:
                    print("month or day error!")
            else:
                print( "len > 3")
        else:
            print("can not find the right pattern")
        return (None, None, None)

class OrderExcelReader(object):
    class ColumnIndexes(IntEnum):
        DIGEST = 1      #B
        INCOME = 2      #C
        PAYOUT = 3     #D
        #remark = ????  #???
    class RowIndexes(IntEnum):
        DATE_TIME = 1
        VALUE_START = 4

    def __init__(self, file_path):
        self.__excel = Excel.from_file(file_path)
        assert self.__excel is not None
        self.__sheet_name = "Sheet1"


    #move to Excel.Row,  row.get(Index, default)
    def as_default(self, row, index, default=None):
        value = row[index].value
        return  value if value is not None else default

    def is_buy_order(self, row):
        digest = row[OrderExcelReader.ColumnIndexes.DIGEST].value
        payout = row[OrderExcelReader.ColumnIndexes.PAYOUT].value
        return  digest is not None and payout is not None
    
            
    def parse_date_time_str(self, dt_str):
        return DateTimeStringParser(dt_str).parse()

    def get_date_time(self, row, index):
        dt = row[index].value
        if dt is not None and len(dt) > 0:
            (year, month, day) = self.parse_date_time_str(dt.strip())
            print(f"{year},{month},{day})")
            return datetime.datetime(year, month, day)
        return None
        

    def read_all(self):
        if not self.__excel.exists(self.__sheet_name):
            logging.error("sheet:{} not exists in file".format(self.__sheet_name));
            return None

        sheet = self.__excel.sheet("Sheet1")
        result = []
        buy_date_time = None
        for (index, row) in enumerate(sheet.rows()):
            if index == OrderExcelReader.RowIndexes.DATE_TIME:
                buy_date_time = self.get_date_time(row, 0)

            if index < OrderExcelReader.RowIndexes.VALUE_START: #skip the table head
                logging.warning(f"Skip header of sheet: RowIndex:{index}, row:{row}")
                continue

            if self.is_buy_order(row):
                digest = self.as_default(row, OrderExcelReader.ColumnIndexes.DIGEST, "")
                price = self.as_default(row, OrderExcelReader.ColumnIndexes.PAYOUT, 0.0)
                amount = 1
                bo = BuyOrder(
                    digest=digest,
                    amount=amount,
                    price=price,
                    buy_date_time = buy_date_time
                )
                result.append(bo)
                
            #elif self.is_sell_order(row) TODO:
            else:
                logging.warning(f"Skip rows, not the buy_order: index:{index}, row:{row}")
        return result



import unittest 
class TestExcelReading(unittest.TestCase):
    def test_main(self):
        file_path = "/home/chenglun/tmp/上海荣鹭园艺有限公司资金收支平衡表.xlsx" 
        buy_orders = OrderExcelReader(file_path).read_all()
        for item in buy_orders:
            print(str(item))

    def test_parse(self):
        s = ["2022年11月12日" ,
            "2022年11月2日" ,
            "2022年1月2日" ,
            "2022年1月12日",
            "2022年05月02日",
        ]

        for item in s:
            (year, month, day) = DateTimeStringParser(item).parse()
            assert year is not None
            assert month is not None
            assert day is not None

